package de.hmm.hwip.storage.service;

import java.util.Hashtable;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.util.tracker.ServiceTracker;

import android.content.Context;
import android.util.Log;

import de.hmm.hwip.general.IAndroidContext;
import de.hmm.hwip.storage.api.ISQLite;

/**
 * OSGi Storage Service
 * provides Service to save Data in Database
 * 
 * @author johannes mendel
 * @version 24.09.2012
 *
 */
public class Activator implements BundleActivator {
	
	/**OSGi Interface for Android Context **/
	IAndroidContext contextService;
	
	/** OSGi Interface for database communication **/
	ISQLite dbService;
	
	private static ServiceTracker contextServiceTracker;
	
	static Context androidContext;
	
	private String TAG = "Storage Service Activator";

	
	@Override
	public void start(BundleContext context) throws Exception {
		Log.i(TAG, "=========== de.hmm.hwip.storage.service =========== started ===========");

		//contextService = new AndroidActivity();
		dbService = new SQLiteStorageImpl();

		Hashtable<String, Object> dbparams = new Hashtable<String, Object>();
    	dbparams.put( org.osgi.framework.Constants.SERVICE_PID, ISQLite.class.getName());
    	dbparams.put( org.osgi.framework.Constants.SERVICE_DESCRIPTION,"Provides DB Service");
    	context.registerService(ISQLite.class.getName(), dbService, dbparams);
    	
    	contextServiceTracker = new ServiceTracker(context, IAndroidContext.class.getName(), null);
    	contextServiceTracker.open();
    	contextService = (IAndroidContext) contextServiceTracker.getService();
    	
    	if(contextService != null){
    		androidContext = contextService.transferContext();
    	}else{
    		Log.w(TAG, "Android Context Service is null");
    	}
	}

	@Override
	public void stop(BundleContext arg0) throws Exception {
		Log.i(TAG,"... Storage Service stopped ...");

	}
	
	public static Context getAndroidContext(){
		return androidContext;
	}
}
